var App = App||{};
App.Calendar = { };
App.Calendar.init = function(){
	this.today = new Date().toStr();
	
	$(window).bind('hashchange', function(){ App.Week.load.call(App.Week, location.hash.substr(1)); });
	
	// Datepicker
	this.picker = $('#calendar')
			.datepicker({ dateFormat: 'yy-mm-dd', firstDay: 1, changeMonth: true, changeYear: true,
				onClose: function(dateText, inst){ $(this).trigger('dateChange', [ dateText ]); }
			})
			.bind('dateChange', $.proxy(this.dateChange, this));
	
	// Date Navigation
	this.btnPrev = $("#btnPrevDay").bind('click', $.proxy(this.prevWeek, this));
	this.btnNext = $("#btnNextDay").bind('click', $.proxy(this.nextWeek, this));
	
	$("#lnkLastWeek").bind('click', $.proxy(this.toLastWeek, this));
	$("#lnkThisWeek").bind('click', $.proxy(this.toThisWeek, this));
	

	if (location.hash.length>1) {
		this.date = location.hash.substr(1);
		this.picker.val(this.date);
		App.Week.load.call(App.Week, location.hash.substr(1));
	}
	else {
		this.date = new Date().toStr();
		this.dateChange(null, this.date);
	}
	 
};


/**
 * Custom event handler - occurs when the calendar date has been changed
 */
App.Calendar.dateChange = function(e, dateStr){
	this.date = dateStr;
	this.picker.val(dateStr);
	location.hash = dateStr;
};

App.Calendar.addDays = function(days){ this.picker.trigger('dateChange', [ this.date.toDate().addDays(days).toStr() ]); };
App.Calendar.prevWeek = function(){ this.addDays(-7); };
App.Calendar.nextWeek = function(){ this.addDays(7); };
App.Calendar.toThisWeek = function(){ this.picker.trigger('dateChange', [ new Date().toStr() ]); return false; };
App.Calendar.toLastWeek = function(){ this.picker.trigger('dateChange', [ new Date().addDays(-7).toStr() ]); return false; };
